﻿using Microsoft.SharePoint.Client;
using System;
using System.Net;

namespace Office365.SharePointOnline.Cmdlets
{
    [System.Management.Automation.Cmdlet(System.Management.Automation.VerbsCommon.Set, "JSLink")]
    public class Update_JSLink : System.Management.Automation.PSCmdlet
    {
        [System.Management.Automation.Parameter(Position = 0, Mandatory = true)]
        public string Url;

        [System.Management.Automation.Parameter(Position = 1, Mandatory = false)]
        public string User;

        [System.Management.Automation.Parameter(Position = 2, Mandatory = false)]
        public string Password;

        [System.Management.Automation.Parameter(Position = 3, Mandatory = false)]
        public string AuthenticationMethod;

        // use only if onpremise authentication
        [System.Management.Automation.Parameter(Position = 4, Mandatory = false)]
        public string Domain;

        [System.Management.Automation.Parameter(Position = 5, Mandatory = false)]
        public string FieldName;

        [System.Management.Automation.Parameter(Position = 6, Mandatory = false)]
        public string JSlinkUrl;

        protected override void ProcessRecord()
        {
            // check parameters
            ClientContext context = new ClientContext(Url);
            ICredentials credentials;
            Web web = context.Web;
            this.WriteVerbose("Logging on.");
            if (string.IsNullOrEmpty(Url))
            {
                this.WriteObject("Error: url is not set");
            }
            else
            {
                if (!string.IsNullOrEmpty(Password) && !string.IsNullOrEmpty(User))
                {
                    AuthenticationHelper authenticationHelper = new AuthenticationHelper() { AuthenticationMethod = AuthenticationMethod, Domain = Domain, Password = Password, User = User };
                    credentials = authenticationHelper.GetCredentials();
                    if (credentials != null)
                    {
                        context.Credentials = credentials as ICredentials;
                    }
                    else
                    {
                        throw new NullReferenceException("No credentials returned.");
                    }
                }
                else
                {
                    this.WriteVerbose("Reusing existing credentials");
                }

                this.WriteVerbose("Updating JSlink.");
                context.Load(web);
                context.ExecuteQuery();

                UpdateJSlink(context, web);
            }
        }

        private void UpdateJSlink(ClientContext context, Web web)
        {
            var fields = web.AvailableFields;
            context.Load(fields);
            context.ExecuteQuery();
            this.WriteVerbose("Available fields");
            foreach (var avfield in fields)
            {
                this.WriteObject(avfield.InternalName);
            }
            try
            {
                this.WriteVerbose(string.Format("Getting the field {0}.", FieldName));
                var field = fields.GetByInternalNameOrTitle(FieldName);
                context.Load(field);
                context.ExecuteQuery();
                if (field == null)
                {
                    this.WriteVerbose("Nothing found");
                }
                else
                {
                    this.WriteVerbose(string.Format("Old value: {0}", field.JSLink));
                    this.WriteVerbose(string.Format("Updating field {0} JSLink to {1}.",FieldName,JSlinkUrl));
                    field.JSLink = JSlinkUrl;
                    field.Update();
                    context.Load(field);
                    context.ExecuteQuery();
                }
            }
            catch (Exception ex)
            {
                this.WriteObject(string.Format("Could not find field to update: {0}", ex.Message));
            }
        }
    }
}
